package dao

import (
	"github.com/go-xorm/xorm"
	"log"
	"lottery/models"
)

type UserDao struct {
	engine *xorm.Engine
}

func NewUserDao(engine *xorm.Engine) *UserDao {
	return &UserDao{engine: engine}
}

func (d *UserDao) Get(id int) (has bool, data *models.TbUser) {
	data = &models.TbUser{Id: id}
	has, err := d.engine.Get(data)
	if has && err == nil {
		return
	} else {
		data.Id = 0
		return
	}
}

func (d *UserDao) GetByUsername(username string) (has bool, data *models.TbUser) {
	data = &models.TbUser{}
	has, err := d.engine.Where("username=?", username).Get(data)
	if has && err == nil {
		return
	} else {
		return
	}
}

func (d *UserDao) GetByOpenId(openId string) (has bool, data *models.TbUser) {
	data = &models.TbUser{}
	has, err := d.engine.Where("openid=?", openId).Get(data)
	if has && err == nil {
		return
	} else {
		return
	}
}

func (d *UserDao) IsUserExist(username string) bool {

	exist, err := d.engine.Exist(&models.TbUser{Username: username})
	if err != nil {
		log.Println("user_dao.IsUserExist() failed, err=", err)
	}
	return exist
}

func (d *UserDao) GetAll() []models.TbUser {
	dataList := make([]models.TbUser, 0)
	err := d.engine.Find(&dataList)
	if err != nil {
		log.Println("user_dao.GetAll() failed, err=", err)
	}
	return dataList
}

func (d *UserDao) Update(data *models.TbUser, columns []string) error {
	_, err := d.engine.Where("id=?", data.Id).MustCols(columns...).Update(data)
	return err
}

func (d *UserDao) Create(data *models.TbUser) error {
	_, err := d.engine.Insert(data)
	return err
}

func (d *UserDao) Delete(id int) error {
	data := &models.TbUser{Id: id, Status: 5}
	_, err := d.engine.Where("id=?", id).Update(data)
	return err
}
